package com.mars.basic.controller.admincontroller;

import com.mars.basic.allmain.entity.PermissionEntity;
import com.mars.basic.allmain.po.Permission;
import com.mars.basic.allmain.vo.PermissionVo;
import com.mars.common.utils.ApiResult;
import com.mars.basic.service.PermissionService;
import com.mars.common.expetion.SysException;
import com.mars.common.utils.QAssert;
import com.mars.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Marvrick
 */
@RestController
@RequestMapping(value = "/admin/permission",name = "权限管理")
public class APermissionController {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private ConfigurableApplicationContext run;

    /**
     * 添加权限
     *
     * @param vo
     * @return
     */
    @RequestMapping(value = "/add",name = "添加权限")
    public ApiResult addPermission(@RequestBody PermissionVo vo) {
        QAssert.isTrue(vo.getName() != null, SysException.class, "权限名称不能为空");
        QAssert.isTrue(!permissionService.checkPermissionIsExit(vo), SysException.class, "该权限名称或者url已存在");
        PermissionEntity build = vo.build();
        permissionService.getPermissionRepository().save(build);
        return ApiResult.ok("添加成功");
    }

    /**
     * 查询权限
     *
     * @return
     */
    @RequestMapping(value = "/list",name = "查询权限")
    public R getPermissionList() {
        List<PermissionEntity> all = permissionService.getPermissionRepository().findAll();
        return R.data(all);
    }

    /**
     * 整理权限
     *
     * @return
     */
    @RequestMapping(value = "/organize",name = "整理权限")
    public R AutoAddPermission() {
        //获取数据库中所有权限
        List<String> allUrls = permissionService.getAllUrls();
        ArrayList<String> list = new ArrayList<>();
        list.add("/my/test1");
        list.removeAll(allUrls);
        List<Permission> permissions = permissionService.getMyUrls(run);
        List<Permission> permissionList = permissions.stream().filter(permission -> !allUrls.contains(permission.getUrl())).collect(Collectors.toList());
        System.out.println(permissionList);
        return R.data(permissionList);
    }


}
